package com.xiaobawang.xjsyy_idea_plugin.panel.config.view;

import com.intellij.openapi.application.ApplicationManager;
import com.xiaobawang.xjsyy_idea_plugin.global.GlobalConfig;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.swing.*;
import java.awt.*;

/**
 * @author synhard
 * @description TODO
 * @date 2024/5/22 15:50
 * @email songxinhang2023@e-chinalife.com
 * @id 18101119
 * @phone 13001321080
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class TokenPanel extends JPanel {
    private JTextField tokenLabel;
    private JButton toggleButton;
    private JButton setButton;
    private boolean isMasked = true; // 初始为脱敏状态

    // 定义Token更新的回调接口
    public interface OnTokenUpdateListener {
        void onTokenUpdated();
    }

    private OnTokenUpdateListener tokenUpdateListener;

    // 在doOKAction中调用这个方法来更新tokenLabel
    private void updateTokenDisplay() {
        tokenLabel.setText(isMasked ? maskToken() : GlobalConfig.token);
    }

    public TokenPanel() {
        this.setLayout(new FlowLayout());
        this.tokenLabel = new JTextField(maskToken());
        this.tokenLabel.setEditable(false);
        this.toggleButton = new JButton("显示");
        this.setButton = new JButton("设置");

        toggleButton.addActionListener(e -> {
            isMasked = !isMasked;
            tokenLabel.setText(isMasked ? maskToken() : GlobalConfig.token);
            toggleButton.setText(isMasked ? "显示" : "隐藏");
        });

        setButton.addActionListener(e -> {
            ApplicationManager.getApplication().invokeLater(() -> {
                if (new TokenDialog(this::updateTokenDisplay).showAndGet()) {
                    if (tokenUpdateListener != null) {
                        tokenUpdateListener.onTokenUpdated();
                    }
                }
            });
            super.repaint();
        });
        add(new JLabel("token: "));
        add(this.tokenLabel);
        add(this.setButton);
        add(this.toggleButton);
    }

    // 修改maskToken方法
    private String maskToken() {
        return "*".repeat(GlobalConfig.token.length());
    }
}
